import { defineComponent, provide, ref, toRef, watch, watchEffect } from 'vue';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
// import { TMenu,TList TItem } from 't';
import TDateTime from 't/basic/date-time'
import TInput from 't/basic/input'
import TIcon from 't/basic/icon'
import TPopupProxy from 't/basic/popup-proxy';
import TBanner from 't/basic/banner';
import TBtn from 't/basic/button';

import { useQuasar } from '@teld/q-components';

import FilterLayout from './filter-layout.jsx';
import { filterRowWithDate, useOperationProps } from './use-col-filter.js';

export default defineComponent({
  name: 'TDataGridColFilterDate',
  props: {
    ...useOperationProps,
  },
  emits: ['update:operation', 'change'],

  setup(props, { attrs, emit, expose, slots }) {
    const filterOperations = ['=', '<>', '<', '<=', '>', '>=', 'between'];
    const operation = toRef(props.operation);
    dayjs.extend(customParseFormat)

    const $q = useQuasar();

    provide('operation', operation);
    watchEffect(() => {
      emit('update:operation', operation.value);
      emit('change');
    });
    // watch(
    //   () => operation.value.filterValue,
    //   () => {
    //     emit('change', operation.value?.filterValue);
    //   },
    // );

    const renderDataInput = () => {
      return (
        <FilterLayout filterOperations={filterOperations}>
          <TDateTime
            dateType={props.dataType}
            format24h={true}
            todayBtn={true}
            nowBtn={true}
            with-seconds
            borderless
            outlined={false}
            v-model={operation.value.filterValue}
          />
        </FilterLayout>
      );
    };

    const startValue = ref();

    const endValue = ref();

    const betweenValue = ref();

    const updateBetweenValue = () => {
      debugger;
      // let sValue = startValue.value ? dayjs(startValue.value).format("YYYY-MM-DD") : "?";
      // let eValue = endValue.value ? dayjs(endValue.value).format("YYYY-MM-DD") : "?";
      // return [sValue, eValue].join(' ~ ');
      return [refStartValue.value.value.inputValue.value || '?', refEndValue.value.value.inputValue.value || '?'].join(' ~ ');
      // return [startValue.value || '?', endValue.value || '?'].join(' ~ ');
    };

    watch(
      () => betweenValue.value,
      () => {
        if (startValue.value || endValue.value) {
          operation.value.filterValue = [startValue.value, endValue.value];
        } else {
          operation.value.filterValue = '';
        }
      },
    );
    watch(
      () => props.operation.name,
      val => {
        if (val == 'between') {
          betweenValue.value = '';
          startValue.value = '';
          endValue.value = '';
        }
      },
    );

    const betweenPopupValue = ref();

    const dateBetweenErrMsg = ref(false);

    const refStartValue = ref();
    const refEndValue = ref();

    const conform = () => {
      dateBetweenErrMsg.value = filterRowWithDate(startValue.value, {
        name: '>',
        dataType: operation.value.dataType,
        filterValue: endValue.value,
      });
      if (false == dateBetweenErrMsg.value) {
        betweenValue.value = updateBetweenValue();
        betweenPopupValue.value = false;
      }
    };

    const changeDataBetween = e => {
      if (null == e) {
        startValue.value = '';
        endValue.value = '';
      } else {
        startValue.value = e[0];
        endValue.value = e[1];
      }
      betweenValue.value = [
        startValue.value || '?',
        endValue.value || '?',
      ].join(' ~ ');
    };

    const renderDataBetween = () => {
      return (
        <FilterLayout filterOperations={filterOperations}>
          <TDateTime
            dateType={props.dataType == 'date' ? 'daterange' : 'datetimerange'}
            onChange={changeDataBetween}
            // displayFormatWithDateTime='YYYY/MM/DD HH:mm:ss'
          />
        </FilterLayout>
      );
    };

    const renderDataBetween_v1 = () => {
      return (
        <>
          <FilterLayout filterOperations={filterOperations}>
            {{
              default: () => (
                <TInput
                  borderless
                  outlined={false}
                  readonly
                  v-model={betweenValue.value}
                  showClearButton={true}
                  dense={true}
                  filled={false}
                  hideLabel={true}
                >
                  {{
                    append: () => (
                      <TIcon
                        name='event'
                        icon='event'
                        size='xs'
                        class='cursor-pointer'
                      >
                        <TPopupProxy
                          class='row q-pa-sm'
                          self='top end'
                          v-model={betweenPopupValue.value}
                          offset={[-50, 0]}
                        >
                          <TBanner>
                            <div class='q-col-gutter-y-md'>
                              <div
                                class={[
                                  $q.platform.is.mobile
                                    ? 'column q-col-gutter-y-md'
                                    : 'row q-col-gutter-x-md',
                                ]}
                              >
                                <div>
                                  <TDateTime
                                    placeholder={
                                      $q.lang.dataGrid?.filterOperation?.startDate
                                    }
                                    dateType={props.dataType}
                                    ref={refStartValue}
                                    v-model={startValue.value}
                                  />
                                </div>
                                <div>
                                  <TDateTime
                                    placeholder={
                                      $q.lang.dataGrid?.filterOperation?.endDate
                                    }
                                    ref={refEndValue}
                                    dateType={props.dataType}
                                    v-model={endValue.value}
                                  />
                                </div>
                              </div>
                              <div class='row q-col-gutter-x-md items-center justify-end'>
                                {dateBetweenErrMsg.value && (
                                  <div class='text-negative'>
                                    {
                                      $q.lang.dataGrid?.filterOperation?.dateBetweenErrMsg
                                    }
                                  </div>
                                )}
                                <div>
                                  <TBtn
                                    class='tr-button-default'
                                    onClick={() => {
                                      betweenPopupValue.value = false;
                                    }}
                                    label={$q.lang.dataGrid?.cancel}
                                  />
                                </div>
                                <div>
                                  <TBtn
                                    color='primary'
                                    onClick={conform}
                                    label={$q.lang.dataGrid?.confirm}
                                  />
                                </div>
                              </div>
                            </div>
                          </TBanner>
                        </TPopupProxy>
                      </TIcon>
                    ),
                  }}
                </TInput>
              ),
            }}
          </FilterLayout>
        </>
      );
    };

    return () => {
      return 'between' == operation.value.name
        ? renderDataBetween()
        : renderDataInput();
    };
  },
});
